
<template>
  <div
    class="pageContain"
    style="color: black; width: 100%; background: #efefef; overflow: hidden"
  >
    <div class="pageContainBack divBeteewn">
      <div class="anlyLeft">
        <div class="selectAndSearch">
          <div class="search searchSelect">
            <el-select
              placeholder="选择类型"
              v-model="selectType"
              @change="selectTypeChange()"
            >
              <el-option label="电" :value="1"></el-option>
              <el-option label="燃气" :value="2"></el-option>
              <el-option label="水表" :value="3"></el-option>
              <el-option label="光伏" :value="4"></el-option>
            </el-select>
          </div>
          <div class="search">
            <el-input v-model="input4"></el-input>
            <div class="searchIcon divCenter" @click="getTypeUseNenegery()">
              <img src="@/assets/img/searchIcon.png" alt="" />
            </div>
          </div>
        </div>

        <el-table
          :data="addDeviceList1"
          @selection-change="selecttableFunction"
          style="width: 88%; height: auto; margin: auto; margin-top: 2vh"
          :header-cell-style="{ height: '3vh', color: 'black' }"
          max-height="75vh"
        >
          <el-table-column
            type="selection"
            prop="全选"
            align="center"
            width="50"
          />
          <el-table-column
            prop="name"
            align="left"
            label="全选"
          ></el-table-column>
          <el-table-column prop="number" label=""></el-table-column>
        </el-table>
      </div>
      <div class="anlyRight">
        <div class="search divFlex">
          <div class="selectContain">
            <el-select
              style="width: 5vw"
              v-model="dateSelect"
              @change="selectChange()"
            >
              <el-option label="日" value="日"></el-option>
              <el-option label="月" value="月"></el-option>
              <el-option label="年" value="年"></el-option>
            </el-select>
          </div>
          <div class="dataContain">
            <el-config-provider :locale="locale">
              <el-date-picker
                v-if="dateSelect == '日'"
                v-model="startTime"
                type="date"
                placeholder="年-月-日"
                style="width: 8vw; margin-left: 1vw"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
              <el-date-picker
                v-if="dateSelect == '月'"
                v-model="startTime"
                type="month"
                placeholder="年-月"
                style="width: 8vw; margin-left: 1vw"
                format="YYYY-MM"
                value-format="YYYY-MM"
              >
              </el-date-picker>
              <el-date-picker
                v-if="dateSelect == '年'"
                v-model="startTime"
                style="width: 8vw; margin-left: 1vw"
                type="year"
                placeholder="年"
                format="YYYY"
                value-format="YYYY"
              >
              </el-date-picker>
            </el-config-provider>
          </div>
          <div class="buttonSearch divCenter" @click="getSearchCompare()">
            <div class="searchButtonIcon">
              <img src="@/assets/img/blackSearch.png" alt="" />
            </div>
            <div class="buttonSearchText">查询</div>
          </div>
          <div class="buttonSearch divCenter">
            <div class="searchButtonIcon">
              <img src="@/assets/img/blackexcel.png" alt="" />
            </div>
            <div class="buttonSearchText" @click="excelExport()">导出</div>
          </div>
        </div>
        <div class="search">
          <el-table
            v-if="selectType !== 4"
            :data="dataList"
            ref="exportTableRef"
            style="height: auto"
            max-height="74vh"
            class="exportTableRef"
            :header-row-style="{
              height: '6vh',
              fontSize: '1vw',
              color: 'white',
              background: '#005EBC',
            }"
            :row-style="{ height: '6vh' }"
          >
            <el-table-column align="center" prop="name" label="设备名称">
            </el-table-column>
            <el-table-column
              align="center"
              prop="current"
              :label="current"
            ></el-table-column>
            <el-table-column
              align="center"
              :label="last"
              prop="last"
            ></el-table-column>
            <el-table-column align="center" :label="increace">
              <template #default="scope">
                <div>
                  {{ formatNumber(scope.row.current - scope.row.last) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="环比(%)">
              <template #default="scope">
                <div class="compareLast divCenter">
                  <div>
                    {{ countNumber(scope.row.current, scope.row.last) }}
                  </div>
                  <div
                    class="compareUp"
                    v-if="scope.row.current - scope.row.last > 0"
                  ></div>
                  <div
                    class="compareDown"
                    v-else-if="scope.row.current - scope.row.last < 0"
                  ></div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            v-if="selectType == 4"
            :data="dataList"
            ref="exportTableRef"
            class="exportTableRef"
            style="height: auto"
            :header-row-style="{
              height: '6vh',
              fontSize: '1vw',
              color: 'white',
              background: '#005EBC',
            }"
            max-height="74vh"
            :row-style="{ height: '6vh' }"
          >
            <el-table-column align="center" prop="name" label="设备名称">
            </el-table-column>
            <el-table-column
              align="center"
              prop="current"
              label="本期用电量(KW.h)"
            ></el-table-column>
            <el-table-column
              align="center"
              label="同期用电量(KW.h)"
              prop="last"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="current1"
              label="本期上网电量(KW.h)"
            ></el-table-column>
            <el-table-column
              align="center"
              label="同期上网电量(KW.h)"
              prop="last1"
            ></el-table-column>
            <el-table-column align="center" label="增加值(kw.h)">
              <template #default="scope">
                <div>
                  {{ formatNumber(scope.row.current - scope.row.last) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="环比(%)">
              <template #default="scope">
                <div class="compareLast divCenter">
                  <div>
                    {{ countNumber(scope.row.current, scope.row.last) }}
                  </div>
                  <div
                    class="compareUp"
                    v-if="scope.row.current - scope.row.last > 0"
                  ></div>
                  <div
                    class="compareDown"
                    v-else-if="scope.row.current - scope.row.last < 0"
                  ></div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import sendMessage from "@/mitt/sendMessage.js";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import service from "@/api/api";
import * as XLSX from "xlsx";
import { getToday } from "@/mitt/until";
const cityOptions = [
  { name: "item1", number: "XXXXXXXXX", id: 1 },
  { name: "item2", number: "XXXXXXXXX", id: 2 },
  { name: "item3", number: "XXXXXXXXX", id: 3 },
  { name: "item4444", number: "XXXXXXXXXXX", id: 4 },
];
export default {
  beforeRouteEnter(to, from, next) {
    sendMessage(3, "设备用能分析");
    next();
  },

  data() {
    return {
      addDeviceList1: [
        { deviceName: "设备1", number: "SNXXXX1", id: 1 },
        { deviceName: "设备2", number: "SNXXXX2", id: 2 },
      ],
      multi: [],
      selectLong: "",
      selectType: 1,
      date1: "",
      locale: zhCn,
      timeType: 1,
      input4: "",
      checkAll: false,
      checkedCities: [1, 2],
      cities: cityOptions,
      isIndeterminate: true,
      deviceNumberList: [],
      dateSelect: "日",
      dataList: [],
      current: "本期(kw.h)",
      last: "同期(kw.h)",
      increace: "增加值(kw.h)",
      startTime: "",
      endTime: "",
    };
  },
  props: [],
  components: {},
  computed: {},
  filters: {},
  methods: {
    formatNumber(num) {
      if (Number.isInteger(num)) {
        return num.toString(); // 整数直接返回字符串形式
      } else {
        return num.toFixed(2); // 小数保留 2 位
      }
    },
    countNumber(current, previous) {
      // 处理null值情况
      const a = current === null ? 0 : current;
      const b = previous === null ? 0 : previous;

      // 情况1：a和b同时为0
      if (a === 0 && b === 0) {
        return "0%";
      }

      // 情况2：a存在但b不存在或为0
      if (b === 0) {
        return "100%";
      }

      // 正常情况计算环比增长率
      const growthRate = ((a - b) / b) * 100;

      // 格式化输出：整数不带小数，非整数保留两位小数
      const rounded = Math.round(growthRate * 100) / 100;
      return rounded % 1 === 0 ? `${rounded}%` : `${rounded.toFixed(2)}%`;
    },

    selectTypeChange() {
      if (this.selectType == 1) {
        this.current = "本期(kw.h)";
        this.last = "同期(kw.h)";
        this.increace = "增加值(kw.h)";
      } else if (this.selectType == 2) {
        this.current = "本期(m³)";
        this.last = "同期(m³)";
        this.increace = "增加值(m³)";
      } else if (this.selectType == 3) {
        this.current = "本期(m³)";
        this.last = "同期(m³)";
        this.increace = "增加值(m³)";
      } else if (this.selectType == 4) {
        this.current = "本期(kw.h)";
        this.last = "同期(kw.h)";
        this.increace = "增加值(kw.h)";
      }

      this.getTypeUseNenegery();

      console.log(this.dataList);
    },

    selecttableFunction(row) {
      if (row.length > 0) {
        this.multi = [];
        row.forEach((element) => {
          this.multi.push(element.number);
        });
      } else {
        this.multi = [];
      }
    },
    selectChange() {
      if (this.dateSelect == "日") {
        this.timeType = 1;
      } else if (this.dateSelect == "月") {
        this.timeType = 3;
      } else if (this.dateSelect == "年") {
        this.timeType = 4;
      }
      this.startTime = "";
    },
    handleCheckAllChange(val) {
      // this.checkedCities = val ? cityOptions.name : [];
      this.checkedCities = [];
      if (val) {
        cityOptions.forEach((item) => {
          this.checkedCities.push(item.id);
        });
      }

      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 文件导出
    excelExport() {
      if (this.dataList.length < 1) {
        return this.$message({
          message: "无数据",
          type: "warning",
        });
      }
      // const tableDom = this.$refs.exportTableRef.value?.$el;
      // if (!tableDom) {
      //   return;
      // }
      const tableDom = document.getElementsByClassName("exportTableRef")[0];
      let name = "";
      if (this.selectType == 1) {
        name = "电";
      } else if (this.selectType == 2) {
        name = "燃气";
      } else if (this.selectType == 3) {
        name = "水表";
      } else if (this.selectType == 4) {
        name = "光伏";
      }
      const wb = XLSX.utils.table_to_book(tableDom);
      XLSX.writeFile(wb, name + "数据.xlsx");
    },
    // 获取用能分类用电情况
    async getTypeUseNenegery() {
      let data = {};
      if (this.input4) {
        data = {
          text: this.input4,
          deviceType: this.selectType,
        };
      } else {
        data = {
          deviceType: this.selectType,
        };
      }
      let res = await service({
        method: "get",
        url: "/device-energy-analysis/device-by-type",
        params: data,
      });

      this.addDeviceList1 = res.data;
      this.dataList = [];
    },
    async getSearchCompare() {
      if (!this.startTime) {
        return this.$message({
          message: "时间参数不可缺少",
          type: "warning",
        });
      } else if (this.multi.length < 1) {
        return this.$message({
          message: "请先勾选设备",
          type: "warning",
        });
      }
      let data = {
        dateTime: this.startTime,
        deviceNumberList: this.multi + "",
        timeType: this.timeType,
      };
      this.dataList = [];
      let res = await service({
        method: "get",
        url: "/device-energy-analysis/energy-analysis",
        params: data,
      });

      this.dataList = [];
      res.data.forEach((item) => {
        this.dataList.push({
          name: item[0],
          current: item[1],
          current1: item[2],
          last: item[3],
          last1: item[4],
        });
      });
    },
  },
  created() {
    this.getTypeUseNenegery();

    this.startTime = getToday();
  },
  mounted() {},
  beforeUnmount() {
    // Vue 3（Vue 2 用 beforeDestroy）
  },
};
</script>
<style lang="less" scoped>
.el-table {
  font-size: 0.8vw;
}
.anlyLeft {
  :deep(.el-table__cell) {
    padding: 0 !important;
  }
  :deep(.el-table__cell .cell) {
    display: flex;
    align-items: center;
    // justify-content: center;

    padding-left: 0.5vw !important;
    // height: 7vh !important;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
  }
  :deep(.el-checkbox__inner) {
    box-shadow: 0 0 0 1px #0281b8 inset;
  }
  :deep(.el-table .el-checkbox__inner) {
    transform: scale(1.5); /* 放大1.5倍 */
    /* 增加外边距避免重叠 */
  }
}
.compareLast {
  .compareUp,
  .compareDown {
    width: 0.7vw;
    height: 2.6vh;
    min-width: 14px;
    min-height: 28px;
  }
  .compareUp {
    background: url(@/assets/img/compareUp.png);
    background-size: 100% 100%;
  }
  .compareDown {
    background: url(@/assets/img/compareDown.png);
    background-size: 100% 100%;
  }
}
.anlyRight {
  .search {
    :deep(.el-table td.el-table__cell) {
      border-bottom: 1px solid #a4a6a7;
    }
    :deep(.el-table tr:last-child td) {
      border-bottom: none;
    }
  }
}
.checkBoxContainner {
  width: 100%;
  max-height: 700px;
  overflow: auto;
}

.searchContain {
  width: 100%;
  height: 600px;
  border: 1px solid black;
  margin-top: 20px;
}
.anlyLeft {
  width: 30%;
  height: 89vh;
  background: white;
  .selectAndSearch {
    width: 87%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: auto;
  }
  .search {
    width: 48%;
    height: 4vh;
    position: relative;
    // background: red;
    margin: auto;
    margin-top: 2vh;
    .searchIcon {
      position: absolute;
      top: 0;
      width: 2vw;
      height: 4vh;
      right: 0;
      background-size: 100% 100%;
      img {
        width: 1.25vw;
        height: 1.25vw;
      }
    }
    :deep(.el-input__wrapper) {
      height: 4vh;
      background: #efefef !important;

      box-shadow: none;
      border: 1px solid #0281b8;
      padding-right: 2vw;
    }
  }
}
.el-input {
  font-size: 0.8vw;
}
.anlyRight {
  width: 69%;
  height: 89vh;
  background: white;
  .search {
    width: 93%;
    height: 4vh;
    // background: red;
    margin: auto;
    margin-top: 2vh;
    .selectContain {
      width: 5vw;
      height: 4vh;
      :deep(.el-select__wrapper) {
        height: 4vh !important;
        background: #efefef !important;
        // box-shadow: 0 0 0 1px #0281b8 inset;
      }

      :deep(.el-select__selected-item) {
        font-size: 0.8vw;
        height: 4vh;
        display: flex;
        align-items: center;
        // box-shadow: 0 0 0 1px #0281b8 inset;
      }
    }
    .dataContain {
      height: 4vh;
      :deep(.el-date-editor) {
        height: 4vh !important;
      }
      :deep(.el-input__inner) {
        height: 4vh;
      }
      :deep(.el-input__wrapper) {
        height: 4vh !important;
        background: #efefef;
        // margin: 0;
        // padding: 0;
      }
      :deep(.el-input__icon) {
        font-size: 1vw !important;
      }
      :deep(.el-input__inner) {
        font-size: 0.8vw;
        color: black;
      }
    }
    .buttonSearch {
      width: 6.4vw;
      cursor: pointer;
      height: 4vh;
      background: #005ebc;
      margin-left: 1vw;
      .searchButtonIcon {
        width: 1.2vw;
        height: 1.2vw;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .buttonSearchText {
        width: 3vw;
        font-size: 1vw;
        padding-left: 0.5vw;
        color: white;
      }
    }
  }
}
.searchSelect {
  :deep(.el-select__wrapper) {
    height: 4vh !important;
    background: #efefef !important;
    // box-shadow: 0 0 0 1px #0281b8 inset;
  }

  :deep(.el-select__selected-item) {
    font-size: 0.8vw;
    height: 4vh;
    display: flex;
    align-items: center;
    // box-shadow: 0 0 0 1px #0281b8 inset;
  }
}
</style>
